package org.csu.chatroom.Netty;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;

public class SimpleServerHandler extends ChannelInboundHandlerAdapter {

    private String nickname;
    private static final Map<String, String> USER_CREDENTIALS = new HashMap<>();  // 存储用户的用户名和密码
    private NettyServer nettyServer;  // 手动传入 NettyServer
    private Room currentRoom;
    public SimpleServerHandler(NettyServer nettyServer) {
        this.nettyServer = nettyServer;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 当客户端连接时，添加到在线用户列表
        nettyServer.addChannel(ctx.channel());
        System.out.println("客户端 " + ctx.channel().remoteAddress() + " 上线");
    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // 当客户端断开时，从在线用户列表中移除
        nettyServer.removeChannel(ctx.channel());
        System.out.println("客户端 " + ctx.channel().remoteAddress() + " 下线");
//        currentRoom.removeUser(ctx.channel());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception{

        ByteBuf byteBuf  = (ByteBuf) msg;
        String jsonMessage = byteBuf.toString(CharsetUtil.UTF_8);  // 将 ByteBuf 转换为字符串
        System.out.println("收到客户端消息: " + byteBuf .toString(CharsetUtil.UTF_8));
        // 使用 Jackson 序列化工具将消息解析为 Message 对象
        ObjectMapper mapper = new ObjectMapper();
        Message message = mapper.readValue(jsonMessage, Message.class);

        // 根据消息类型进行处理
        String messageType = message.getHeader().getMessageType();
        String payload = message.getPayload();

        // 处理心跳包
        if ("HEARTBEAT".equals(messageType)) {
            // 如果收到的是心跳包，更新心跳时间戳
            nettyServer.updateHeartbeat(ctx.channel());
            System.out.println("收到来自 " + ctx.channel().remoteAddress() + " 的心跳包 💓");
            return;
        }

        // 处理昵称
        if (nickname == null) {
            nickname = payload;  // 第一次接收到的消息是昵称
            System.out.println("昵称: " + nickname);
        } else if (currentRoom == null) {
            // 如果当前没有房间，则为用户加入房间
            Room room = nettyServer.getRoom(payload);
            if (room == null) {
                room = nettyServer.createRoom(payload);  // 创建新的聊天室
            }
            currentRoom = room;
            room.addUser(ctx.channel());
            room.broadcastMessage(nickname + " 已加入 " + payload + " 📢");
        } else {
            // 如果已经在房间中，则直接发送消息到房间
            currentRoom.broadcastMessage(nickname + ": " + payload + " 💬");
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
